package com.sisgr.modelo.servico;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import java.io.IOException;
import java.util.Arrays;
import org.springframework.stereotype.Component;

/**
 * Classe que implementa o protocolo de autenticação OAuth para a Google Data
 * API
 *
 * @author Alessandro
 */
@Component
public class OAuthService {

    //Id da aplicação cadastrada no Google API acess
    private static final String CLIENT_ID = "765264297950-85t1jkefue9r32n04hnuhemu6gv00mpg.apps.googleusercontent.com";
    // Private Key
    private static final String CLIENT_SECRET = "hOvcRQp4WvmUF3Oca1lhkMOX";
    //Uri de retorno após autenticação
    private static final String CALLBACK_URI = "http://localhost:8080/sisgr/home/";
    //Atributos iniciáis de autenticação do Google
    private static final Iterable<String> SCOPE = Arrays.asList("https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email".split(";"));
    private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";
    private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    private final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
            JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPE).build();
    /**
     * Cria a URI que interliga a Google Acounts para autorização do usuário 
     * @return
     */
    public String buildLoginUrl() {
        GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
        return url.setRedirectUri(CALLBACK_URI).setState("google").build();
    }

    /**
     * Retorna as informações do usuário no formato JSON. A operação para
     * resgatar as informações do OAuth é feita via URL
     *
     * @param authCode
     * @return
     * @throws IOException
     */
    public String getUserInformationJson(String authCode) throws IOException {
        GoogleTokenResponse response = flow.newTokenRequest(authCode).setRedirectUri(CALLBACK_URI).execute();
        Credential credential = flow.createAndStoreCredential(response, null);
        HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
        GenericUrl url = new GenericUrl(USER_INFO_URL);
        HttpRequest request = requestFactory.buildGetRequest(url);
        request.getHeaders().setContentType("application/json");
        String jsonIdentity = request.execute().parseAsString();
        return jsonIdentity;
    }
}
